package com.inifitness.common.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

import com.inifitness.common.tools.ThreadMdcUtil;

import cn.hutool.core.text.CharSequenceUtil;
import org.slf4j.MDC;

/**
 * 自定义 ThreadFactory
 * <p>
 * 重命名线程池
 *
 * @author sunjinfeng
 * @since 2022/2/13 0:14
 */
public class NamedThreadFactory implements ThreadFactory {

  public final String namePrefix;
  private final AtomicInteger poolNumber = new AtomicInteger(1);
  private final AtomicInteger threadNumber = new AtomicInteger(1);

  public NamedThreadFactory(String name) {
    if (CharSequenceUtil.isBlank(name)) {
      namePrefix = "pool" + "-" + poolNumber.getAndIncrement() + "-thread-";
    }else {
      namePrefix = name + "-" + poolNumber.getAndIncrement() + "-thread-";
    }
  }

  @Override
  public Thread newThread(Runnable r) {
    Thread t = new Thread(ThreadMdcUtil.wrap(r, MDC.getCopyOfContextMap()),
        namePrefix + threadNumber.getAndIncrement());
    if (t.isDaemon()) {
      t.setDaemon(false);
    }

    if (t.getPriority() != Thread.NORM_PRIORITY) {
      t.setPriority(Thread.NORM_PRIORITY);
    }
    return t;
  }
}
